﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;

namespace ExcelJsonParser
{
    class JsonViewWorkSheet : JsonWorkSheetBase
    {
        JsonWorkSheetTable _jsonWorkSheetTable;
        Range _jsonSource = null;
        public Range JsonSource { get { return _jsonSource; } }
        public Worksheet WorkSheet { get { return _worksheet; } }
        private JsonViewWorkSheet(Worksheet ws):base(ws)
        {
            startY = 2;
        }
        public static JsonViewWorkSheet NewJsonViewWorkSheet(JsonViewWorkBook jsonVWb, Range jsonSource)
        {
            Worksheet ws = jsonVWb.AddEmptySheet(); // JsonWorkApp.GetInstance().GetJsonViewWorkBook().AddEmptySheet();
            JsonViewWorkSheet jsonViewWs = new JsonViewWorkSheet(ws);
            jsonViewWs._jsonSource = jsonSource;
            jsonViewWs.RefreshFromJsonSource();
            return jsonViewWs;
        }

        private void RefreshFromJsonSource()
        {
            object javaObject = JsonWorkCell.GetJsonValueFromCell(_jsonSource);
            //if (javaObject == null || javaObject is JsonUndefined)
            //{
            //    return;
            //}
            Range startCell = _worksheet.Columns[1].Rows[1];
            _jsonWorkSheetTable = new JsonWorkSheetTable(startCell,javaObject);
            foreach (Worksheet ws in ((Workbook)_worksheet.Parent).Sheets)
            {
                if (_worksheet.Equals(ws))
                {
                    ws.Visible = XlSheetVisibility.xlSheetVisible;
                }
                else
                {
                    ws.Visible = XlSheetVisibility.xlSheetVeryHidden;
                }
            }
            ((Workbook)_worksheet.Parent).Windows[1].Visible = true;
            _worksheet.Activate();
        }

        public void UpdateJsonViewWorkSheet(Range jsonSource)
        {
            _jsonSource = jsonSource;
            RefreshFromJsonSource();
        }
    }
}
